<template>
  <div class="flex flex-col overflow-hidden relative">
    <LlCalendar
      v-model="query.date"
      :visible-type.sync="visibleType"
      @confirm="() => switChover()"
      @month-change="getTodoCount"
      :formatter="_dateFormatter"
      @show-up-date="showUpDate"
      style="box-shadow: 0px 2px 4px 0px rgba(159, 159, 159, 0.06)"
    />

    <div class="flex-1 flex flex-col overflow-hidden">
      <div
        class="py-14px px-10px flex justify-between items-center text-dark-300 font-500"
      >
        <div class="text-18px">{{ query.date }}</div>
        <div
          class="flex items-center bg-white px-10px py-6px rounded-16px text-14px"
        >
          <span
            class="p-4px flex items-center rounded-1/1"
            style="background: #f5894e"
          >
            <Icon :name="IconClock" :size="12" />
          </span>
          <span class="ml-8px">{{ todoListAll.todoTotal }}件待办事项</span>
        </div>
      </div>
      <div class="flex-1 overflow-auto px-10px pb-10px" ref="workbenchList">
        <PullRefresh
          v-model="refreshing"
          @refresh="onRefresh"
          class="min-h-full"
        >
          <List
            v-model="loading"
            :finished="finished"
            :finished-text="todoList.length ? '没有更多了' : ''"
            :immediate-check="false"
            @load="onLoad"
          >
            <template
              v-if="todoList.length === 0 && !loading && !switChoverLoading"
            >
              <div
                class="h-full flex-1 flex flex-col justify-center"
                ref="emptyData"
              >
                <Empty :image="emptyIcon" image-size="34">
                  <div slot="description" class="text-dark-300 select-none">
                    暂无待办事项
                  </div>
                </Empty>
              </div>
            </template>
            <template v-else>
              <template v-for="(item, index) in todoList">
                <!-- 待办 -->
                <TodoItem
                  v-if="item.dataType == 1"
                  :key="index"
                  :item="item"
                  @view="() => handleView(item)"
                  @cancel="() => handleCancel(item)"
                  @confirm="() => handleConfirm(item)"
                  @apply="() => handleApply(item)"
                  @clock-in="() => handleClockIn(item)"
                  @clock-out="() => handleClockOut(item)"
                  @follow="() => handleFollow(item)"
                  @refuse="() => handleRefuse(item)"
                  @accept="() => handleAccept(item)"
                />
                <!-- 通知 -->
                <NoticeItem
                  v-else
                  :key="item.id"
                  :item="item"
                  @view="() => handleNoticeView(item)"
                />
              </template>
            </template>
            <div class="text-center" v-if="switChoverLoading">
              <Loading class="scrollLoadingStatus" size="16px"
                ><span class="text-14px">加载中...</span></Loading
              >
            </div>
          </List>
        </PullRefresh>
      </div>
    </div>
    <FloatButton />
  </div>
</template>

<script>
import _ from "lodash";
import moment from "moment";
import { Empty, Icon, Toast, PullRefresh, List, Loading } from "vant";
import LlCalendar from "@/components/ll-calendar";
import TodoItem from "./components/todoItem.vue";
import NoticeItem from "./components/noticeItem.vue";
import FloatButton from "./components/floatButton.vue";
import emptyIcon from "@/assets/icon/empty.png";
import IconClock from "@/assets/icon/clock.png";
import { fetchTodoCount, fetchTodoList, fetchStoreProcess } from "@/services";
import Bus from "@/config/evenrBus";
export default {
  components: {
    PullRefresh,
    List,
    Empty,
    Icon,
    LlCalendar,
    TodoItem,
    NoticeItem,
    FloatButton,
    Loading,
  },
  data() {
    return {
      emptyIcon,
      IconClock,
      query: {
        date: moment().format("YYYY-MM-DD"),
      },
      visibleType: "mini",
      refreshing: false,
      loading: false,
      finished: false,
      todoList: [],
      todoListAll: {},
      showClock: false, // 签到签出弹窗
      clockType: "clock-in", // 默认签到
      clockOptions: {
        poi: [],
      },
      todoCountMap: {},
      page: {
        pageNum: 1,
      },
      switChoverLoading: false,
      workListScrollTop: 0,
    };
  },
  created() {
    const workbenchListStore = this.$store.state.work.workbenchListStore;
    if (!workbenchListStore.load) {
      this.initData();
      this.refreshDataLoad();
    } else {
      this.page.pageNum = workbenchListStore.pageNum;
      this.query.date = workbenchListStore.date;
      this.todoList = workbenchListStore.todoList;
    }
  },
  activated() {
    if (this.$store.state.work.loadDataWork) {
      this.refreshDataLoad();
      this.initData();
    }
    if (this.$refs.workbenchList) {
      //回跳兼容公私海
      this.$refs.workbenchList.scrollTop =
        this.$store.state.work.workListScrollTop;
    }
  },
  deactivated() {
    this.$store.commit(`work/set_workListScrollTop`, {
      value: this.workListScrollTop,
    });
  },
  mounted() {
    //监听滚动
    if (this.$refs.workbenchList) {
      this.$refs.workbenchList.addEventListener("scroll", this.scrollWorkbench);
    }
  },
  methods: {
    onRefresh() {
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.finished = true;
      this.page.pageNum = 1;
      this.loading = true;
      this.initData();
    },
    initData() {
      // 重新加载数据
      this.loading = true;
      this.getTodoCount(this.query.date);
      this.getTodoList();
    },
    switChover() {
      this.loading = false;
      this.refreshing = false;
      this.refreshDataLoad();
      this.switChoverLoading = true;
      this.getTodoList("NoContact");
    },
    /**
     * 重新刷新数据
     */
    refreshDataLoad() {
      this.page.pageNum = 1;
      this.todoList = [];
      this.todoListAll = {};
    },
    /**
     * 获取数量
     */
    async getTodoCount(date) {
      try {
        const { countMap } = await fetchTodoCount({
          start: moment(date).startOf("month").format("YYYY-MM-DD"),
          end: moment(date).endOf("month").format("YYYY-MM-DD"),
        });
        this.todoCountMap = countMap || {};
      } catch (err) {
        Toast(err.errMessage || err.message);
      }
    },
    /**
     * 获取列表
     */
    getTodoList: _.throttle(function (data) {
      //参数汇总
      let params = {
        pageNum: this.page.pageNum,
        start: this.query.date,
        end: this.query.date,
      };
      fetchTodoList(params)
        .then((res) => {
          if (this.refreshing) {
            this.todoList = [];
            this.todoListAll = {};
            this.refreshing = false;
          }
          if (data == "NoContact") {
            //不拼接数据
            this.todoList = res.data;
          } else {
            this.todoList = this.todoList.concat(res.data);
          }
          this.todoListAll = res;
          this.loading = false;
          this.refreshing = false;
          this.switChoverLoading = false;
          // 数据全部加载完成
          if (this.todoList.length >= res.total) {
            this.finished = true; //暂无更多数据
          } else {
            this.finished = false;
          }
          this.noDataHeight();
        })
        .catch((err) => {
          console.log(err);
          this.todoList = [];
          this.refreshing = false;
          this.loading = false;
          this.finished = true; //加载完成
          Toast.fail(err);
          this.noDataHeight();
        });
    }, 300),
    /**
     * 设置没有内容的高度
     */
    noDataHeight() {
      this.$nextTick(() => {
        if (this.$refs.workbenchList) {
          let height = this.$refs.workbenchList.clientHeight;
          let tempDom = this.$refs.emptyData;
          if (this.todoList.length === 0 && !this.loading) {
            tempDom.style.height = height - 10 + "px";
          } else {
            if (tempDom) {
              tempDom.style.height = null;
            } else {
              let isData = document.querySelector(".van-list__finished-text");
              if (isData) {
                isData.style.height = null;
              }
            }
          }
        }
      });
    },
    /**
     * 展开时间重新设置
     */
    showUpDate(val) {
      if (val) {
        this.noDataHeight();
      }
    },
    /**
     * 上拉触底
     */
    onLoad: _.throttle(function () {
      ++this.page.pageNum;
      this.getTodoList();
    }, 300),

    /**
     * 重置加载数据
     */
    loadDataWork() {
      this.$store.commit(`work/set_loadDataWork`, {
        value: false,
      });
    },
    /**
     * 重置公私海加载数据
     */
    privateSeaLoadDataWork() {
      this.$store.commit(`work/set_workbenchListStore`, {
        value: {
          pageNum: this.page.pageNum, //分页
          date: this.query.date, //日期
          todoList: this.todoList, //数据
          load: true,
        },
      });
    },
    /**
     * 外出申请
     */
    handleApply({ type, id }) {
      this.loadDataWork(); //重置加载数据
      this.$router.push({
        path: "/workbench/apply",
        query: {
          id,
          type: type,
          load: "set_loadDataWork",
        },
      });
    },
    /**
     * 签到
     */
    handleClockIn({ type, id }) {
      this.loadDataWork(); //重置加载数据
      this.$router.push({
        path: "/workbench/clock-in",
        query: {
          id,
          type,
          load: "set_loadDataWork",
        },
      });
    },
    /**
     * 签出
     */
    handleClockOut({ type, id }) {
      this.loadDataWork(); //重置加载数据
      this.$router.push({
        path: "/workbench/clock-out",
        query: {
          id,
          type,
          load: "set_loadDataWork",
        },
      });
    },
    /**
     * 跟进
     */
    handleFollow({ type, id }) {
      this.loadDataWork(); //重置加载数据
      this.$router.push({
        path: "/workbench/follow",
        query: {
          id,
          type,
          load: "set_loadDataWork",
        },
      });
    },
    /**
     * 查看详情
     */
    handleView({ id, type, todoStatus, isValid }) {
      this.loadDataWork(); //重置加载数据
      this.$router.push({
        path: "/workbench/view",
        query: {
          id,
          type,
          status: isValid === 1 ? 70 : todoStatus,
        },
      });
    },
    // 外出取消
    handleCancel({ type, id }) {
      this.loadDataWork(); //重置加载数据
      this.$router.push({
        path: "/workbench/cancel",
        query: {
          id,
          type: type,
          load: "set_loadDataWork",
        },
      });
    },
    // 消息详情
    handleNoticeView({ type, id, businessOpportunityId }) {
      this.privateSeaLoadDataWork(); //重置公私海加载数据
      if (type === 1 || type === 2) {
        // 商机转移他人/继承商机详情
        this.$router.push({
          path: "/business/TemporaryLibrary",
          query: { id: businessOpportunityId },
        });
      } else if (type === 3 || type === 4) {
        // 本站BD录入外区商机/外站BD录入本站商机详情
        this.$router.push({
          path: "/business/OuterZone",
          query: { id: businessOpportunityId },
        });
      }
    },
    // 拒绝接收 0
    handleRefuse({ id }) {
      fetchStoreProcess({ shopMoveId: id, accept: 0 })
        .then(() => {
          this.getTodoList();
        })
        .catch((err) => {
          Toast(err.errMessage || err.message);
        });
    },
    // 同意接收 1
    handleAccept({ id }) {
      fetchStoreProcess({ shopMoveId: id, accept: 1 })
        .then(() => {
          this.getTodoList();
        })
        .catch((err) => {
          Toast(err.errMessage || err.message);
        });
    },
    _dateFormatter(day) {
      const dateStr = moment(day.date).format("YYYY-MM-DD");
      if (
        Object.keys(this.todoCountMap).includes(dateStr) &&
        day.type !== "selected"
      ) {
        day.className = "has-todo";
      }
      return day;
    },
    scrollWorkbench() {
      // 声明dom
      var workbenchListDom = this.$refs.workbenchList;
      //顶部距离
      var scrollTop = workbenchListDom.scrollTop;
      //记录滚动的高度
      this.workListScrollTop = scrollTop;
    },
  },
  destroyed() {
    Bus.$off("Details");
    if (this.$route.path == "/business") {
      this.$store.commit(`work/set_workbenchListStore`, {
        value: {},
      });
    }
  },
};
</script>

<style lang="scss" scoped></style>
